package jsu.lipengcheng.trafficnet.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyRabbitConfig {

    /**
     * 自定义消息转换器
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 使用 RabbitTemplateCustomizer 定制 RabbitTemplate
     * 不会参与 rabbitTemplate 的创建过程，避免循环依赖
     */
    @Bean
    public RabbitTemplateCustomizer rabbitTemplateCustomizer() {
        return rabbitTemplate -> {
            // 设置你自定义的 MessageConverter
            rabbitTemplate.setMessageConverter(messageConverter());

            // 设置 Confirm 回调
            rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
                System.out.println("Confirm: " + ack + ", cause: " + cause);
            });

            // 设置 Return 回调
            rabbitTemplate.setReturnsCallback(returnedMessage -> {
                System.out.println("Return: " + returnedMessage.getMessage() +
                        ", code: " + returnedMessage.getReplyCode());
            });

            // 必须开启
            rabbitTemplate.setMandatory(true);
        };
    }
}